package misc

import (
	"fmt"
	"reflect"
	"strconv"
	"strings"

	"gopkg.in/mgo.v2/bson"
)

func Guid() string {
	return bson.NewObjectId().Hex()
}

func Index(vs []string, t string) int {
	for i, v := range vs {
		if v == t {
			return i
		}
	}
	return -1
}

func Include(vs []string, t string) bool {
	return Index(vs, t) >= 0
}

func IsEmpty(a interface{}) bool {
	v := reflect.ValueOf(a)
	if v.Kind() == reflect.Ptr {
		v = v.Elem()
	}
	return v.Interface() == reflect.Zero(v.Type()).Interface()
}

func ToString(any interface{}, defaultStr string) string {
	if v, ok := any.(string); ok {
		return v
	} else {
		return defaultStr
	}
}

//开关量转换
func Val2Unit(un string, val int64) string {

	sval := strconv.FormatInt(val, 10)
	v := fmt.Sprintf("*%s", sval)

	idx := strings.Index(un, v)

	if idx == -1 {
		return sval
	}

	start := idx + len(v)
	un = un[start:len(un)]
	end := strings.Index(un, "#")
	return un[1:end]
}

//字符串添加引号
func QuoteStr(strs []string) []string {
	for i, str := range strs {
		str = `'` + str + `'`
		strs[i] = str
	}

	return strs
}

//userAgent判断登录类型(web/app)
func JudgeTypeFromUserAgent(agent string) string {
	slogintype := "web"
	appkeywords := []string{"Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser"}
	for _, v := range appkeywords {
		if strings.Contains(agent, v) {
			slogintype = "app"
			break
		}
	}
	return slogintype
}
